package com.shenfa.action.systemManager;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;

import com.bank.sdb.util.encryption.PasswordEncryption;
import com.opensymphony.xwork2.ActionSupport;
import com.shenfa.bean.Person;
import com.shenfa.bean.Role;
import com.shenfa.dao.systemManager.role.RoleDao;
import com.shenfa.service.systemManager.person.PersonService;

/**
 * 登陆
 * 
 * @author Administrator
 * 
 */
public class PortalAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	private String loginname;
	private String password;
	private HttpServletRequest request;
	private List<String> roleIds;
	private List<Role> rolelist;
	private String errormsg;

	@Autowired
	private PersonService personService;
	@Autowired
	private RoleDao roleDao;
	// @Autowired
	private Logger log = Logger.getLogger(PortalAction.class);

	public String login() {
		log.debug("login:name=" + loginname + ",psw=" + password);
		String flag = "";
		Person person = personService.getPersonInfos(loginname);
		request = ServletActionContext.getRequest();
		if (null == person) {
			errormsg = "账号或密码错误！";
			flag = "error";
		} else if (PasswordEncryption.verifyPassword(person.getPassword(),
				password)) {
			// 获取人员角色
			rolelist = roleDao.getRoleListByPersonId(person.getId());
			person.setRolelist(rolelist);
			// 保存登陆人信息
			request.getSession().setAttribute("login", person);
			if (null != person) {
				// 为1标识已登录
				if ("1".equals(person.getS_ip())) {
					errormsg = "账号已登录！";
					flag = "error";
				} else {
					Person per = new Person();
					per.setId(person.getId());
					per.setS_ip("1");
					personService.logStateUp(per);
					flag = "login";
				}
			}
		} else {
			errormsg = "账号或密码错误！";
			flag = "error";
		}
		return flag;
	}

	/**
	 * 根据用户编号获取对应的所属角色列表
	 * 
	 * @param personNo
	 * @return
	 */
	private List<String> roleNames(String personNo) {
		List<String> rolenamelist = new ArrayList<String>();
		Role role = new Role();
		roleIds = roleDao.getRoleIdListByPersonId(personNo);
		for (int i = 0; i < roleIds.size(); i++) {
			role = roleDao.getRole(roleIds.get(i));
			if (null != role) {
				rolenamelist.add(role.getName());
			}
		}
		return rolenamelist;
	}

	/**
	 * 用户注销
	 * 
	 * @return
	 */
	public String logout() {
		ServletActionContext.getRequest().getSession().invalidate();
		return "logout";
	}

	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getErrormsg() {
		return errormsg;
	}
}
